<template>
  <div class="container">
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="page-title text-2xl font-bold">个人信息</h1>
        <p class="text-gray-500">查看和编辑您的个人资料信息</p>
      </div>
    </div>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="hover" class="card-with-hover">
          <div class="text-center">
            <el-avatar :size="100" class="mb-4 border-4 border-primary">
              {{ userInfo.name ? userInfo.name.charAt(0) : 'U' }}
            </el-avatar>
            <h2 class="text-xl font-bold mb-2">{{ userInfo.name }}</h2>
            <p class="text-gray-500 mb-4">{{ userInfo.role === 'admin' ? '系统管理员' : '普通用户' }}</p>
            
            <el-divider />
            
            <div class="info-list text-left">
              <div class="info-item flex py-2">
                <span class="info-label text-gray-500 w-24">账号：</span>
                <span class="info-content">{{ userInfo.username }}</span>
              </div>
              <div class="info-item flex py-2">
                <span class="info-label text-gray-500 w-24">手机号：</span>
                <span class="info-content">{{ userInfo.phone }}</span>
              </div>
              <div class="info-item flex py-2">
                <span class="info-label text-gray-500 w-24">邮箱：</span>
                <span class="info-content">{{ userInfo.email }}</span>
              </div>
              <div class="info-item flex py-2">
                <span class="info-label text-gray-500 w-24">部门：</span>
                <span class="info-content">{{ userInfo.department }}</span>
              </div>
              <div class="info-item flex py-2">
                <span class="info-label text-gray-500 w-24">创建时间：</span>
                <span class="info-content">{{ userInfo.createTime }}</span>
              </div>
              <div class="info-item flex py-2">
                <span class="info-label text-gray-500 w-24">最后登录：</span>
                <span class="info-content">{{ userInfo.lastLoginTime }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card shadow="hover" class="card-with-hover">
          <template #header>
            <div class="flex items-center">
              <el-icon class="mr-2"><EditPen /></el-icon>
              <span class="font-bold">编辑个人资料</span>
            </div>
          </template>
          
          <el-form 
            ref="formRef" 
            :model="form" 
            :rules="rules" 
            label-width="120px"
            class="form-container"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" disabled />
            </el-form-item>
            
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
            
            <el-divider content-position="left">修改密码</el-divider>
            
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input v-model="form.oldPassword" type="password" placeholder="请输入旧密码" show-password />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="form.newPassword" type="password" placeholder="请输入新密码" show-password />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitForm" :loading="submitLoading">保存修改</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import { getUserInfo } from '@/utils/auth'

export default {
  name: 'UserProfile',
  components: {
    EditPen
  },
  setup() {
    // 用户信息
    const userInfo = ref({
      id: 1,
      username: 'admin',
      name: '管理员',
      phone: '13800138000',
      email: 'admin@example.com',
      department: '系统管理部',
      role: 'admin',
      createTime: '2023-01-01 00:00:00',
      lastLoginTime: '2023-06-15 10:30:45'
    })
    
    // 表单引用
    const formRef = ref(null)
    const submitLoading = ref(false)
    
    // 表单数据
    const form = reactive({
      username: '',
      name: '',
      phone: '',
      email: '',
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符之间', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      oldPassword: [
        { required: false, message: '请输入旧密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: false, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符之间', trigger: 'blur' }
      ],
      confirmPassword: [
        { 
          validator: (rule, value, callback) => {
            if (form.newPassword && value !== form.newPassword) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ]
    }
    
    // 获取用户信息
    const fetchUserInfo = () => {
      // 实际项目中应从API获取
      /*
      try {
        const res = await userApi.getInfo()
        Object.assign(userInfo.value, res.data)
        initForm()
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
      */
      
      // 使用本地存储的用户信息
      const localUserInfo = getUserInfo()
      if (localUserInfo) {
        Object.assign(userInfo.value, localUserInfo)
      }
      
      initForm()
    }
    
    // 初始化表单
    const initForm = () => {
      form.username = userInfo.value.username
      form.name = userInfo.value.name
      form.phone = userInfo.value.phone
      form.email = userInfo.value.email
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid, fields) => {
        if (valid) {
          submitLoading.value = true
          
          try {
            // 判断是否修改密码
            const hasPasswordChange = form.oldPassword && form.newPassword && form.confirmPassword
            
            // 实际项目中应调用API
            /*
            const params = {
              name: form.name,
              phone: form.phone,
              email: form.email
            }
            
            if (hasPasswordChange) {
              params.oldPassword = form.oldPassword
              params.newPassword = form.newPassword
            }
            
            await userApi.updateInfo(params)
            */
            
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 1000))
            
            // 更新本地用户信息
            userInfo.value.name = form.name
            userInfo.value.phone = form.phone
            userInfo.value.email = form.email
            
            ElMessage.success('个人信息更新成功')
            
            // 如果修改了密码，清空密码字段
            if (hasPasswordChange) {
              form.oldPassword = ''
              form.newPassword = ''
              form.confirmPassword = ''
            }
          } catch (error) {
            ElMessage.error('个人信息更新失败')
            console.error('更新个人信息失败:', error)
          } finally {
            submitLoading.value = false
          }
        } else {
          console.error('表单验证失败:', fields)
        }
      })
    }
    
    // 重置表单
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      initForm()
    }
    
    // 初始化
    onMounted(() => {
      fetchUserInfo()
    })
    
    return {
      userInfo,
      formRef,
      form,
      rules,
      submitLoading,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.page-title {
  position: relative;
  margin-bottom: 4px;
}

.page-title::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 40px;
  height: 3px;
  background-color: var(--el-color-primary);
  border-radius: 3px;
}

.card-with-hover {
  transition: all 0.3s;
  border-radius: 8px;
  margin-bottom: 20px;
}

.card-with-hover:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.border-primary {
  border-color: var(--el-color-primary);
}

.info-item {
  border-bottom: 1px dashed #eee;
}

.info-item:last-child {
  border-bottom: none;
}

.form-container {
  padding: 20px 0;
}
</style> 